/**
 * 
 */
package com.eagle.coders.configurator.jdbc;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.apache.ibatis.jdbc.ScriptRunner;


/**
 * @author Anees
 *
 */
public class SqlScriptExecutor {
	
	private DataSource dataSource;
	private ScriptRunner scriptRunner;
	
	public static SqlScriptExecutor instance;
	
	private SqlScriptExecutor(){
		createDataSource();
	}
	
	public static synchronized SqlScriptExecutor getInstance(){
		if(null == instance)
			instance = new SqlScriptExecutor();
		return instance;
	}
	/**
	 * 
	 */
	private void createDataSource(){
		try{
			Context ctx = new InitialContext();
			dataSource =(DataSource)ctx.lookup("java:/PostgresDS");
			
		}catch(Exception e){
			e.printStackTrace();
//			Doing Nothing for the time being
		}
	}
	
	/**
	 * 
	 * @param sqlScript
	 * @throws SQLException
	 * @throws FileNotFoundException
	 */
	public void executeScript(String sqlScript)throws SQLException, FileNotFoundException {
		
//		checking whether values are there
		Connection conn = dataSource.getConnection();
		Statement stmt = conn.createStatement();
		ResultSet rst = stmt.executeQuery("select * from eagle_users");
//		TODO: Need to check from DB-Meta-data 
		if(rst.getFetchSize() == 0){

			String file = this.getClass().getClassLoader().getResource(sqlScript).getFile();
			
			System.out.println("[SqlScriptExecutor] :: executeScript :: "+file);	
			
			System.out.println("======= BASE VALUES ARE GOING TO SET ====================");
//			scriptRunner = new ScriptRunner(dataSource.getConnection());
			
//			scriptRunner.runScript(new BufferedReader(new FileReader(file)));
		}else {

			System.out.println("======= BASE VALUES ARE ALREADY SET ====================");

		}
		
	}
}
